<script setup>
import MwTable from "./component/MwTableCity";
import SearchTable from "./component/SearchCity.vue";
import MwDialog from "@/components/Dialog";
import { ElMessage, ElMessageBox } from 'element-plus';

// import { CirclePlus, VideoPlay } from '@element-plus/icons-vue';
import { ref, reactive, getCurrentInstance, onMounted, watch } from "vue";
// import moment from "moment";

const instance = getCurrentInstance();
const _this = instance.appContext.config.globalProperties; //vue3获取当前this

// 生命周期
onMounted(() => {
  getTableData();
});

let getTableData = () => {
  // 查询city
  let paramsCity = {
    ...pagination,
    ...searchForm
  };
  tablLoading.value = true;
  instance.proxy.$http.get('overview.getCityList', { params: paramsCity }).then(res => {
    let { content, totalElements } = res.data;
    tableData.value = content;
    pagination.total = totalElements;
    tablLoading.value = false;
  }).catch(err => tablLoading.value = false);
};

// 弹框数据
let dialogShow = ref(false);
let dialogTitle = ref(' City');
let dialogState = ref('Add'); //  Add Edit Detail 三种状态 根据状态来判断提交方法
let dialogRef = ref(null);
let dialogFrom = reactive({});
let dialogRules = reactive({
  drivernumber: [
    { required: true, message: 'Please input Camera ID', trigger: 'blur' },
    { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: 'String cannot contain spaces', trigger: 'blur' },
  ],
  name: [
    { required: true, message: 'Please input Model', trigger: 'blur' },
    { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: 'String cannot contain spaces', trigger: 'blur' },
  ]
});
let dialogSubmit = async () => {
  let formEl = dialogRef.value;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let url = dialogState.value == 'Add' ? 'archiveData.insertCity' : 'archiveData.updateCity';
      if (dialogState.value == 'Add') {
        instance.proxy.$http.post(url, dialogFrom).then(res => {
          if (res.success) {
            onSearch();
            dialogClose();
          };
        });
      } else {
        instance.proxy.$http.put(url, dialogFrom).then(res => {
          if (res.success) {
            onSearch();
            dialogClose();
          };
        });
      };
    } else {
      console.err('error submit!', fields);
    };
  });
};

let dialogClose = () => {
  dialogShow.value = false;
  dialogRef.value.resetFields();
  for (let item in dialogFrom) {
    if (dialogFrom[item] instanceof Array) {
      dialogFrom[item] = [];
    } else {
      dialogFrom[item] = '';
    };
  };
};

function openDialog(state) {
  dialogState.value = state;
  dialogShow.value = true;
  for (let item in dialogFrom) {
    delete dialogFrom[item];
  };
};

// 表格数据
const tableData = ref([]);
const tablLoading = ref(false);
const pagination = reactive({
  page: 1,
  size: 10,
  total: 100
});
const searchForm = reactive({});
function onSearch() {
  getTableData();
};
function paginationChange(pagination) {
  onSearch();
};

function onEdit(row) {
  openDialog('Edit');
  for (let i in row) {
    dialogFrom[i] = row[i];
  };
};

function onDelete(row) {
  ElMessageBox.confirm(
    'Delete City ？',
    'Delete',
    {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel'
    }
  )
    .then(() => {
      instance.proxy.$http.delete('archiveData.deleteCity', { data: { id: row.id + '' } }).then(res => {
        onSearch();
        ElMessage({
          type: 'success',
          message: 'City delete success.',
        });
      });
    })
    .catch(() => { });
};

</script>
<template>
  <div class="table_index">
    <SearchTable :searchForm="searchForm" @onSearch="onSearch" @addPeople="openDialog('Add')" />
    <div class="table_content">
      <mw-table v-loading="tablLoading" :data="tableData" :pagination="pagination" @paginationChange="paginationChange" @operate1="onEdit" @operate2="onDelete"></mw-table>
    </div>
  </div>

  <mw-dialog :show="dialogShow" :title="dialogState + dialogTitle" width="430px" @submit="dialogSubmit" @close="dialogClose">
    <el-form ref="dialogRef" class="dialog_form" :inline="true" :model="dialogFrom" label-width="70px" :rules="dialogRules">
      <el-form-item label="ID" prop="id">
        <el-input v-model="dialogFrom.id" class="value_input" placeholder="Enter" clearable disabled />
      </el-form-item>
      <el-form-item label="City" prop="city">
        <el-input v-model="dialogFrom.city" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
    </el-form>
  </mw-dialog>
</template>